package com.example.demo.controller;

import com.example.demo.entity.Teacher;
import com.example.demo.service.TeacherService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.List;

@RestController
@RequestMapping("/api/teachers")
public class TeacherController {

    @Autowired
    private TeacherService teacherService;

    // POST /api/teachers
    // 创建教师 (注册)
    @PostMapping
    public ResponseEntity<?> createTeacher(@RequestBody Teacher
                                                       teacher) {
        // 简单校验
        if (teacher.getTeacherId() == null || teacher.getPassword() == null) {
            return ResponseEntity.badRequest().body("教师工号和密码不能为空");
        }

        // 实际应用中，这里需要处理插入失败（如ID重复）的情况
        if (teacherService.createTeacher(teacher)) {
            return new ResponseEntity<>("教师创建成功", HttpStatus.CREATED);
        } else {
            return new ResponseEntity<>("教师工号已存在或创建失败", HttpStatus.BAD_REQUEST);
        }
    }

    // GET /api/teachers/{id}
    // 根据工号查询教师
    @GetMapping("/{id}")
    public ResponseEntity<Teacher> getTeacherById(@PathVariable("id") String teacherId) {
        return teacherService.findTeacherById(teacherId)
                .map(ResponseEntity::ok)        // 找到则返回 200 OK
                .orElse(ResponseEntity.notFound().build()); // 找不到则返回 404 Not Found
    }

    // GET /api/teachers
    // 查询所有教师
    @GetMapping
    public List<Teacher> getAllTeachers() {
        return teacherService.findAllTeachers();
    }

    // PUT /api/teachers/{id}
    // 更新教师信息
    @PutMapping("/{id}")
    public ResponseEntity<?> updateTeacher(@PathVariable("id") String teacherId, @RequestBody Teacher teacherDetails) {
        teacherDetails.setTeacherId(teacherId); // 确保更新的是路径中的ID

        if (teacherService.updateTeacher(teacherDetails)) {
            return ResponseEntity.ok("教师信息更新成功");
        } else {
            return ResponseEntity.notFound().build();
        }
    }

    // DELETE /api/teachers/{id}
    // 删除教师
    @DeleteMapping("/{id}")
    public ResponseEntity<?> deleteTeacher(@PathVariable("id") String teacherId) {
        if (teacherService.deleteTeacher(teacherId)) {
            return ResponseEntity.noContent().build(); // 204 No Content
        } else {
            return ResponseEntity.notFound().build();
        }
    }
}